package com.appbee.cm.client.nav.presenter;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import javax.inject.Inject;

import com.appbee.cm.shared.data.NavItemProxy;
import com.appbee.core.client.event.EntityChange;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.view.client.AbstractDataProvider;
import com.google.gwt.view.client.HasData;
import com.google.web.bindery.event.shared.HandlerRegistration;

public class NavDataProvider extends AbstractDataProvider<NavItemWrap>
{
	private final HandlerRegistration handlerReg;
	private List<NavItemWrap> data;

	@Inject
	public NavDataProvider(EventBus eventBus)
	{
		handlerReg = EntityChange
				.registerForProxyType(	eventBus,
										NavItemProxy.class,
										new EntityChange.Handler<NavItemProxy>()
										{

											@Override
											public void onChange(EntityChange<NavItemProxy> event)
											{
												Collections
														.sort(	data,
																new Comparator<NavItemWrap>()
																{

																	@Override
																	public int compare(	NavItemWrap o1,
																						NavItemWrap o2)
																	{
																		Integer n1 = o1
																				.getWrappedItem()
																				.getNumber();
																		Integer n2 = o2
																				.getWrappedItem()
																				.getNumber();
																		return n1
																				.compareTo(n2);
																	}

																});
												updateRowCount(	data.size(),
																true);
												updateRowData(0, data);
											}

										});
	}

	public void setData(List<NavItemWrap> data)
	{
		this.data = data;
	}

	@Override
	protected void onRangeChanged(HasData<NavItemWrap> display)
	{
		updateRowCount(data.size(), true);
		updateRowData(0, data);
	}

	public void removeHandler()
	{
		handlerReg.removeHandler();
	}

}
